import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Row, Col, Collapse, Form, Input, Select, Spin } from 'antd';
import dynamic from 'umi/dynamic';
import LoadingComponent from '@/components/PageLoading/index';
import request from '@/utils/request';

const { TextArea } = Input;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 },
  },
};

const textAreaFormItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
};

const DealUserSelect = dynamic({
  loader: () => import('@/pages/FlowComp/DealUserSelect'),
  loading: LoadingComponent,
});

function DealTacheSelect(props) {
  const { getFieldDecorator } = props.form;
  const { onChange } = props;
  const [selectDealUserModalVisible, setSelectDealUserModalVisible] = useState(false);
  const [nextStaffDisplay, setNextStaffDisplay] = useState(true);
  const [isFlowStart, setIsFlowStart] = useState(false);
  const [nextFlowNodeCodeList, setNextFlowNodeCodeList] = useState([]);
  const [dealDisabled, setDealDisabled] = useState(false);
  const [loading, setLoading] = useState(false);
  const [busiObjArgs, setBusiObjArgs] = useState([]);

  const getNextList = params => {
    props.form.setFieldsValue({
      nextFlowNodeId: '',
    });
    setNextFlowNodeCodeList([]);
    // 查询下一环节列表
    request('pmc/pms/PmOrderFlowJumpController/getNextList', {
      data: params,
    }).then(res => {
      // 查询成功
      if (res && res.success === true && res.data) {
        // 正向流程下一环为空，则表示环节结束
        if (res.data.length === 0) {
          // setNextStaffDisplay(false);
        } else {
          props.form.setFieldsValue({
            nextFlowNodeId: `${res.data[0].flowNodeId}`,
          });
          setNextStaffDisplay(true);
          setNextFlowNodeCodeList(res.data);
        }
      }
    });
  };

  const initData = () => {
    const { objInstId, objType, flowId, orderId, execId, value, busiObjArgs } = props;

    // 如果存在值，说明是onChange后再加载
    if (value) {
      props.form.setFieldsValue(value);
      setNextFlowNodeCodeList(value.nextFlowNodeCodeList);
      setNextStaffDisplay(value.nextStaffDisplay);
      setIsFlowStart(value.isFlowStart);
      return;
    }

    let busiObjArgsTmp = [];
    if (typeof busiObjArgs === 'string') {
      busiObjArgsTmp = JSON.parse(busiObjArgs);
      setBusiObjArgs(busiObjArgsTmp);
    }

    props.form.setFieldsValue({
      objInstId,
      objType,
      flowId,
      orderId,
      execId,
    });

    setNextStaffDisplay(false);

    // 工单Id为空，流程还未启动
    if (execId == null) {
      setIsFlowStart(true);
      // 1、查询流程首环节
      request('pmc/pms/PmOrderFlowNodeController/getFirstNode', {
        data: {
          objectId: Date.now(),
          objectType: props.objType,
          busiObjArgs: busiObjArgsTmp,
        },
      }).then(res => {
        if (res && res.success === true && res.data) {
          // 2、通过环节ID执行初始化事件
          request('pmc/pms/PmOrderFlowNodeController/flowNodeInit', {
            data: {
              objectId: Date.now(),
              objectType: props.objType,
              flowNodeId: res.data.flowNodeId,
            },
          }).then(res => {
            console.log(res);
          });

          props.form.setFieldsValue({
            currentFlowId: res.data.flowId,
            currentTacheCode: res.data.flowNodeCode,
          });
          const params = {
            flowId: res.data.flowId,
            currentTacheCode: res.data.flowNodeCode,
          };
          getNextList(params);
        }
      });
    } else {
      const params = {
        execId,
      };
      getNextList(params);
    }
  };

  // 初始化
  useEffect(() => {
    if (props.execId || props.busiObjArgs) {
      initData();
    }
  }, [props.execId, props.busiObjArgs]);

  const dealResult = [
    {
      name: '通过',
      value: '1',
    },
    {
      name: '不通过',
      value: '0',
    },
  ];

  const onFormChange = async () => {
    try {
      await props.form.validateFields();
    } catch (error) {
      return;
    }
    const formData = props.form.getFieldsValue();
    formData.busiObjArgs = busiObjArgs;
    formData.nextFlowNodeCodeList = nextFlowNodeCodeList;
    formData.nextStaffDisplay = nextStaffDisplay;
    formData.isFlowStart = isFlowStart;
    onChange(formData);
  };

  /**
   * 选择处理人模态框控制方法
   * @param flag
   */
  const handleSetSelectDealUserModalVisible = flag => {
    setSelectDealUserModalVisible(flag);
  };

  /**
   * 选中处理人
   */
  const handleOkSelectDealUser = dealUsers => {
    if (dealUsers != null && dealUsers.length > 0) {
      props.form.setFieldsValue({
        // dealObjName: dealUsers[0].userName,
        nextStaff: dealUsers[0].objId,
        objName: dealUsers[0].objName,
        objType: dealUsers[0].objType,
      });
      onFormChange();
    }
  };

  // 选择处理人回调的入参方法
  const SelectDealUserMethods = {
    handleSetSelectDealUserModalVisible,
    handleOkSelectDealUser,
  };

  const chooseNextNodeType = value => {
    let params = {};
    if (props.form.getFieldsValue().execId) {
      params = {
        execId: props.form.getFieldsValue().execId,
      };
    } else {
      params = {
        flowId: props.form.getFieldsValue().currentFlowId,
        currentTacheCode: props.form.getFieldsValue().currentTacheCode,
      };
    }

    getNextList(params);

    // 清空下一步处理人
    const dealUser = {};
    const dealUsers = [dealUser];
    handleOkSelectDealUser(dealUsers);

    if (value === '1') {
      // setDealDisabled(false);
    } else if (value === '0') {
      // 设置之前的环节的处理人 并不可编辑
      // const dealUser = {};
      // const dealUsers = [dealUser];
      // handleOkSelectDealUser(dealUsers);
      // setDealDisabled(true);
    }
    // onFormChange();
  };

  return (
    <>
      {props.mode === 'readOnly' ? null : (
        <Spin spinning={loading} tip="处理中，请稍候。。。">
          <Collapse
            className="cute"
            defaultActiveKey={['1']}
            bordered={false}
            expandIconPosition="right"
          >
            <Collapse.Panel header="环节处理" key="1">
              {
                <Form>
                  <div style={{ display: !isFlowStart ? 'block' : 'none' }}>
                    <Row>
                      <Col span={8}>
                        <FormItem label="处理结果" {...formItemLayout}>
                          {getFieldDecorator('auditPass', {
                            initialValue: '1',
                            rules: [
                              {
                                required: true,
                              },
                            ],
                          })(
                            <Select
                              placeholder="请选择"
                              style={{ width: '100%' }}
                              showSearch
                              onChange={chooseNextNodeType}
                              onBlur={onFormChange}
                            >
                              {dealResult.length
                                ? dealResult.map(item => {
                                    return (
                                      <Select.Option value={item.value} key={item.value}>
                                        {item.name}
                                      </Select.Option>
                                    );
                                  })
                                : null}
                            </Select>
                          )}
                        </FormItem>
                      </Col>

                      <Col
                        span={8}
                        style={{ display: nextFlowNodeCodeList.length ? null : 'none' }}
                      >
                        <FormItem label="下一环节" {...formItemLayout}>
                          {getFieldDecorator('nextFlowNodeId', {
                            rules: [{}],
                          })(
                            <Select placeholder="请选择" style={{ width: '100%' }} showSearch>
                              {nextFlowNodeCodeList.length
                                ? nextFlowNodeCodeList.map(item => {
                                    return (
                                      <Select.Option
                                        value={`${item.flowNodeId}`}
                                        key={`${item.flowNodeId}`}
                                      >
                                        {item.flowNodeName}
                                      </Select.Option>
                                    );
                                  })
                                : null}
                            </Select>
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                  </div>

                  <Row>
                    <Col span={8}>
                      <div style={{ display: nextStaffDisplay ? 'block' : 'none' }}>
                        <FormItem label="下一步处理人" {...formItemLayout}>
                          {getFieldDecorator('objName', {
                            rules: [
                              {
                                required: nextStaffDisplay,
                                message: '请选择下一步处理人',
                              },
                            ],
                          })(
                            <Input.Search
                              readOnly
                              placeholder="请选择处理人"
                              onSearch={() => {
                                handleSetSelectDealUserModalVisible(true);
                              }}
                              disabled={!!dealDisabled}
                            />
                          )}
                        </FormItem>
                      </div>
                    </Col>
                    {/* <Col span={8}>
          <div style={{display: isFlowEnd == false ? "block" : "none"}}>
            <FormItem label="是否短信通知审批人" {...formItemLayout}>
            {getFieldDecorator('isRemind',{
              initialValue: false,
              valuePropName: 'checked',
            })(
              <Switch checkedChildren={<Icon type="check" />}
                // unCheckedChildren={<Icon type="close" />}
              />
            )}
        </FormItem>
          </div>
        </Col> */}
                    <div style={{ display: 'none' }}>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('nextStaff')(<Input />)}</FormItem>
                      </Col>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('objType')(<Input />)}</FormItem>
                      </Col>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('currentFlowId')(<Input />)}</FormItem>
                      </Col>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('currentTacheCode')(<Input />)}</FormItem>
                      </Col>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('objInstId')(<Input />)}</FormItem>
                      </Col>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('flowId')(<Input />)}</FormItem>
                      </Col>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('objType')(<Input />)}</FormItem>
                      </Col>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('orderId')(<Input />)}</FormItem>
                      </Col>
                      <Col span={1}>
                        <FormItem>{getFieldDecorator('execId')(<Input />)}</FormItem>
                      </Col>
                    </div>
                  </Row>

                  <Row>
                    <Col span={16}>
                      <FormItem label="处理意见" {...textAreaFormItemLayout}>
                        {getFieldDecorator('dealContent', {
                          rules: [
                            {
                              required: props.form.getFieldsValue().auditPass !== '1',
                              message: '请填写处理意见',
                            },
                          ],
                        })(<TextArea rows={4} onBlur={onFormChange} />)}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              }

              {selectDealUserModalVisible ? (
                <DealUserSelect
                  {...SelectDealUserMethods}
                  flowNodeId={props.form.getFieldsValue().nextFlowNodeId}
                  modalVisible={selectDealUserModalVisible}
                />
              ) : null}
            </Collapse.Panel>
          </Collapse>
        </Spin>
      )}
    </>
  );
}

export default connect(() => ({}))(Form.create()(DealTacheSelect));
